package com.guazai.project.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.guazai.project.service.FileService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author qiteng
 * @description 用于文件传输的service实现
 * @date 2024-08-14 17:16:21
 */
@Service
public class FileServiceImpl implements FileService {

    /**
     * 阿里云OSS地域节点
     */
    private static final String OSS_Endpoint = "http://oss-cn-guangzhou.aliyuncs.com";

    /**
     * Bucket域名
     */
    private static final String BUCKET_DOMAIN = "https://api-avatar123.oss-cn-guangzhou.aliyuncs.com/";

    /**
     * ACCESS_KEY_ID
     */
    private static final String ACCESS_KEY_ID = "LTAI5tE7Z1icG1Q8WjBt1pyt";

    /**
     * ACCESS_KEY_SECRET
     */
    private static final String ACCESS_KEY_SECRET = "6jecCXXBaXftmhQ6WZUaflLZ79vEfL";

    private static final String BUCKET_NAME = "api-avatar123";


    /**
     * 上传文件到阿里云OSS
     * @return
     */
    public String uploadToAliOss(MultipartFile file) throws IOException {
        //更改文件名
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        UUID uuid = UUID.randomUUID();
        String fileName = uuid + "." + ext;
        //创建oss客户端
        OSS ossClient = new OSSClientBuilder().build(OSS_Endpoint, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        //上传文件
        ossClient.putObject(BUCKET_NAME, fileName, file.getInputStream());
        //关闭oss客户端
        ossClient.shutdown();
        //返回文件名
        return BUCKET_DOMAIN + fileName;
    }

}
